﻿using System;
using System.Collections.Generic;
using Shell.Build;
using Shell.Build.TypeMapping;

namespace Shell
{
    internal class DefaultBuildersExtension : IShellExtension
    {
        private readonly Stack<StagedBuilder> registeredbuilders;

        public DefaultBuildersExtension()
        {
            this.registeredbuilders = new Stack<StagedBuilder>();
        }

        public Guid Identity
        {
            get { return IShellExtensionIdentities.DefaultBuildersExtension; }
        }

        public ShellExtensionContext Context { get; private set; }

        public void Initialize(ShellExtensionContext context)
        {
            this.Context = context;

            var typeMapper = new StagedBuilder(BuildStage.TypeMapping, new TypeMapper());
            this.Context.BuildChainMaker.Add(typeMapper.Stage, typeMapper.Builder);
            this.registeredbuilders.Push(typeMapper);

            var lifetimeBuilder = new StagedBuilder(BuildStage.Lifetime, new LifetimeBuilder());
            this.Context.BuildChainMaker.Add(lifetimeBuilder.Stage, lifetimeBuilder.Builder);
            this.registeredbuilders.Push(lifetimeBuilder);

            var defaultBuilder = new StagedBuilder(BuildStage.PostCreation, new DefaultBuilder());
            this.Context.BuildChainMaker.Add(defaultBuilder.Stage, defaultBuilder.Builder);
            this.registeredbuilders.Push(defaultBuilder);
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                while (this.registeredbuilders.Count > 0)
                {
                    var stagedBuilder = this.registeredbuilders.Pop();
                    this.Context.BuildChainMaker.Remove(stagedBuilder.Stage, stagedBuilder.Builder);
                }
                this.Context = null;
            }
        }

        private class StagedBuilder
        {
            public StagedBuilder(BuildStage stage, IBuilder builder)
            {
                this.Stage = stage;
                this.Builder = builder;
            }

            public BuildStage Stage { get; private set; }

            public IBuilder Builder { get; private set; }
        }
    }
}
